package com.zzttwl.locktcp.handler;

import com.zzttwl.locktcp.serviceImpl.ParseServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ServerHandler extends SimpleChannelInboundHandler<byte[]> {

    protected Log log = LogFactory.getLog(this.getClass());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("连接建立");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("连接断开");
    }

    /**
     * 信息读取完成后即调用此方法
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    /**
     * 检测到有信息发来即调用此方法，用来读取信息
     */
    @Override
    public void channelRead0(final ChannelHandlerContext ctx, final byte[] msg) throws Exception {
        System.out.println(msg);
        log.debug("收到：" + msg);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String hex = parseBytesToHexString(msg);
                new ParseServiceImpl().parseMsg(ctx, hex);
            }
        }).start();
    }

    public static String toHexString2(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            buffer.append(toHexString2(b[i]));
        }
        return buffer.toString();
    }

    public static String toHexString2(byte b) {
        char[] buffer = new char[2];
        buffer[0] = Character.forDigit((b >>> 4) & 0x0F, 16);
        buffer[1] = Character.forDigit(b & 0x0F, 16);
        return new String(buffer);
    }

    //字节数组转16进制字符串
    public static String parseBytesToHexString(byte[] contentByte) {
        String contentStr = "";
        if (contentByte != null && contentByte.length > 0) {
            StringBuilder stringBuilder = new StringBuilder(contentByte.length);
            for (int i = 0; i < contentByte.length; ++i) {
                Object[] objectArray = new Object[]{contentByte[i]};
                stringBuilder.append(String.format("%02X", objectArray));
            }
            contentStr = stringBuilder.toString();
        }
        return contentStr;
    }


    /**
     * 此方法用来捕捉通信过程中的异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable arg1) throws Exception {
        ctx.close();
    }


}
